package com.chookss.login;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.WebCommonActivity;
import com.chookss.base.StaticClass;
import com.chookss.home.other.ScanActivity;
import com.chookss.tools.MyToast;
import com.chookss.tools.RSACoder;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.old.SignUtils;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;

import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginQrCodeActivity extends BaseAct {

    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.llError)
    LinearLayout llError;
    @BindView(R.id.llLogin)
    LinearLayout llLogin;
    private String loginUid,status;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_qr_code);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        loginUid=getIntent().getStringExtra("loginUid");
        status=getIntent().getStringExtra("status");
//        0-未失效 1-已失效
        if("0".equals(status)){
            llError.setVisibility(View.GONE);
            llLogin.setVisibility(View.VISIBLE);
            commonTitleTxt.setText("扫描二维码登录");
        }else{
            llError.setVisibility(View.VISIBLE);
            llLogin.setVisibility(View.GONE);
            commonTitleTxt.setText("二维码登录失效");

        }
    }
    private void check() {
        showLoading();
        Map<String, String> map = new HashMap<>();
        map.put("loginUid", loginUid);
        MyHttpRequest.getRequest(Urls.checkQRStatus, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        if (llError==null) {
                            return;
                        }
                        if("0".equals(jsonObject1.getString("status"))){
                            llError.setVisibility(View.GONE);
                            llLogin.setVisibility(View.VISIBLE);
                            commonTitleTxt.setText("扫描二维码登录");
                        }else{
                            llError.setVisibility(View.VISIBLE);
                            llLogin.setVisibility(View.GONE);
                            commonTitleTxt.setText("二维码登录已失效");
                        }
                    }else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }
    private String username="",password="",companyName="";
    private void login() {
        showLoading();
        Map<String, Object> map = new HashMap<>();
        username=new ShareUtils().getString(this, StaticClass.USERNAME, "");
        password=new ShareUtils().getString(this, StaticClass.ORIGINALPASS, "");
        companyName=new ShareUtils().getString(this, StaticClass.COMPANYNAME, "");
        String encodePassword = "";
        String encodeUsername = RSACoder.encryRas(username);
        map.put("companyName",companyName);
        map.put("username", username);
        if(Utils.isNull(password)){
            map.put("password","");
        }else{
            encodePassword = RSACoder.encryRas(password);
            map.put("password",password);
        }
        map.put("type", "1");
        map.put("loginUid", loginUid);
        String timeStamp = SignUtils.getTimeStamp();//20201208125238
        String nonce = SignUtils.getRandomString(14);
        String makeSignStr = SignUtils.makeSignStr(map, timeStamp, nonce, true);
        Map<String, String> maps = new HashMap<>();
        maps.put("companyName", companyName);
        maps.put("username", encodeUsername);
        if(Utils.isNull(password)){
            maps.put("password", "");
        }else{
            maps.put("password", encodePassword);
        }
        maps.put("type", "1");
        maps.put("loginUid", loginUid);
        maps.put("timestamp", timeStamp);
        maps.put("nonce", nonce);
        maps.put("sign", makeSignStr);
        MyHttpRequest.postRequest(Urls.seachLogin, this, SignUtils2.makeSignStr(maps), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if (llError==null) {
                        return;
                    }
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("登录成功");
                        finish();
                    } else {
                        llError.setVisibility(View.VISIBLE);
                        llLogin.setVisibility(View.GONE);
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    @OnClick({R.id.common_title_back, R.id.tvOk, R.id.tvRetry, R.id.tvCancel})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.tvOk:
                if (Urls.antiShake.check()) {
                    return;
                }
                login();
                break;
            case R.id.tvRetry:
                new IntentIntegrator(this)
                        .setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)// 扫码的类型,可选：一维码，二维码，一/二维码
                        .setPrompt("请对准二维码")// 设置提示语
                        .setCameraId(0)// 选择摄像头,可使用前置或者后置
                        .setBeepEnabled(true)// 是否开启声音,扫完码之后会"哔"的一声
                        .setBarcodeImageEnabled(false)// 扫完码之后生成二维码的图片
                        .setOrientationLocked(false)//扫描方向固定
                        .setCaptureActivity(ScanActivity.class) // 设置自定义的activity是CustomActivity
                        .initiateScan();// 初始化扫码
                break;
            case R.id.tvCancel:
                MyToast.show("取消扫码登录");
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                MyToast.show("扫码取消");
            } else {
                String content = result.getContents();
                KLog.i("扫描成功: " + content);
                Intent intent = null;
                if (content.startsWith("http")) {
                    intent = new Intent(this, WebCommonActivity.class);
                    intent.putExtra("url", content);
                    startActivity(intent);
                    finish();
                } else {
                    loginUid=content;
                    check();
                }

            }
        }
    }
}
